﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Data;

namespace Common
{
    public sealed class CommonMethord
    {
        public static readonly string Third_Order_Payment = "第三方订单支付";
        #region 获取是否是同程自出票订单
        /// <summary>
        /// 获取是否是同程自出票订单
        /// </summary>
        /// <param name="remoteBuyMerchantId">供应商Id</param>
        /// <returns></returns>
        public static bool IsSelfOrder(int remoteBuyMerchantId)
        {
            if (remoteBuyMerchantId == 1427076 || remoteBuyMerchantId == 4205260)
            {
                return true;
            }
            else
            {
                return false;
            }
        }
        #endregion

        #region 是否第三方订单
        /// <summary>
        /// 是否是今日订单
        /// </summary>
        /// <param name="merchantId">代理ID</param>
        /// <returns></returns>
        public static bool IsJinRiOrder(int merchantId)
        {
            return merchantId == 3101276;
        }

        /// <summary>
        /// 是否是8000yi订单
        /// </summary>
        /// <param name="merchantId">代理ID</param>
        /// <returns></returns>
        public static bool IsBaQianYiOrder(int merchantId)
        {
            return merchantId == 4153923;
        }

        /// <summary>
        /// 是否是51Book订单
        /// </summary>
        /// <param name="merchantId">代理ID</param>
        /// <returns></returns>
        public static bool Is51BookOrder(int merchantId)
        {
            return merchantId == 3834665;
        }

        /// <summary>
        /// 是否是百拓订单
        /// </summary>
        /// <param name="merchantId">代理ID</param>
        /// <returns></returns>
        public static bool IsBaiTuoOrder(int merchantId)
        {
            return merchantId == 6728860;
        }

        /// <summary>
        /// 是否是第三方订单
        /// </summary>
        /// <param name="merchantId">代理ID</param>
        /// <returns></returns>
        public static bool IsThirdOrder(int merchantId)
        {
            return IsJinRiOrder(merchantId) || IsBaQianYiOrder(merchantId) || Is51BookOrder(merchantId) || IsBaiTuoOrder(merchantId);
        }
        #endregion

        #region 获取字典数据（根据key得到value）
        /// <summary>
        /// 获取字典数据
        /// </summary>
        /// <param name="key">字典数据的键</param>
        /// <returns></returns>
        public static string GetDictionaryByKey(string key)
        {
            try
            {
                string sql = "select datavalue from [TCFly].[dbo].FlightDataDictionary with(nolock) where datakey='" + key + "' and DataFlag=1";
                sql += SQL.AppendComment("机票Client", "付怀东", "获取字典数据（根据key得到value）", "Util/FlightRule.cs", "GetDictionaryByKey");
                DataTable dt = DBHelper.ExecuteDataTable(sql);
                return dt.Rows[0][0].ToString();
            }
            catch
            {

            }
            return "";
        }

        /// <summary>
        /// 获取字典数据
        /// </summary>
        /// <param name="key">字典数据的键</param>
        /// <param name="type">类型</param>
        /// <returns></returns>
        public static string GetDictionaryByKey(string key, string type)
        {
            string sql = "select datavalue from [TCFly].[dbo].FlightDataDictionary with(nolock) where datakey='" + key + "' and datatype='" + type + "' and DataFlag=1";
            sql += SQL.AppendComment("机票Client", "付怀东", "获取字典数据（根据key得到value）", "Util/FlightRule.cs", "GetDictionaryByKey");
            DataTable dt = DBHelper.ExecuteDataTable(sql);
            if (dt == null || dt.Rows.Count < 1)
            {
                return "";
            }
            else
            {
                return dt.Rows[0][0].ToString();
            }
        }
        #endregion

        #region 更新字典数据
        /// <summary>
        /// 更新字典
        /// </summary>
        /// <param name="key">键</param>
        /// <param name="value">值</param>
        /// <param name="error"></param>
        /// <returns></returns>
        public static bool UpTimeSpanDic(string key, string value, out string error)
        {
            error = string.Empty;
            bool flag = false;
            string strUpDic = string.Format(@"UPDATE dbo.FlightDataDictionary SET DataValue='{0}' WHERE DataKey='{1}'", value, key);
            strUpDic += SQL.AppendComment("机票Service", "FHD", "查询在班责任人队列", "AdminService.Common/CommonMethord.cs.cs", "UpTimeSpanDic");
            if (DBHelper.ExecuteNonQuery(strUpDic) > 0)
            {
                flag = true;
            }
            else
            {
                error = "更新失败！";
                flag = false;
            }
            return flag;
        }
        #endregion

        #region 获取配置的字典值FlightConfigDict
        /// <summary>
        /// 获取配置的字典值
        /// </summary>
        /// <param name="key">键值</param>
        /// <param name="type">类型</param>
        /// <returns>string</returns>
        public static string GetConfigDictByKey(string key, string type)
        {
            string strSQL = string.Format(" SELECT FCDValue FROM FlightConfigDict WITH(NOLOCK) WHERE FCDType='{0}' AND FCDKey='{1}'", type, key);
            DataTable dt = DBHelper.ExecuteDataTable(strSQL);
            if (dt == null || dt.Rows.Count < 1)
            {
                return "";
            }
            else
            {
                return dt.Rows[0][0].ToString();
            }
        }
        #endregion

        #region 更新配置的字典值FlightConfigDict
        /// <summary>
        /// 更新配置的字典值
        /// </summary>
        /// <param name="key">键值</param>
        /// <param name="type">类型</param>
        /// <param name="value">值</param>
        /// <returns>bool</returns>
        public static bool SetConfigDictByKey(string key, string type, string value)
        {
            string strSQL = string.Format(" UPDATE FlightConfigDict SET FCDValue= '{2}' WHERE FCDType='{0}' AND FCDKey='{1}'", type, key, value);
            int result = DBHelper.ExecuteNonQuery(strSQL);
            if (result > 0)
            {
                return true;
            }

            return false;
        }
        #endregion

        #region 插入财务流水账
        /// <summary>
        /// 插入财务流水账
        /// </summary>
        /// <param name="tcOrderId"></param>
        public static void AddFinanceInfo(int tcOrderId, int type)
        {
            try
            {
                HttpRequestHelper.GetRequest(SiteInfo.RootURI +
                    string.Format("Finance/BlotterRecordHandler.ashx?Type={0}&Id={1}", type, tcOrderId));
            }
            catch (Exception ex)
            {
                Logger.WriteLog("调用插入财务流水账接口异常：", ex);
            }
        }
        #endregion

        #region 验证订单是否需要进行重新计价,并返回提示信息
        /// <summary>
        /// 验证订单是否需要进行重新计价,并返回提示信息
        /// </summary>
        /// <param name="orderId"></param>
        /// <param name="orderTypeStr"></param>
        /// <param name="tcflatStr"></param>
        /// <param name="createDateStr"></param>
        /// <returns></returns>
        public static string IsNeedReprice(int orderId, int orderType, int tcflat, DateTime createDate)
        {
            bool isNeedReprice = false;
            string msg = string.Empty;
            if (orderType == 1 && tcflat == 1)
            {
                if (createDate.Day != DateTime.Now.Day)
                {
                    isNeedReprice = true;
                    msg = "订单跨天支付，请确认重新计价！";
                }
                else if (DateTime.Now.AddMinutes(-30) >= createDate)
                {
                    isNeedReprice = true;
                    msg = "订单下单超过30分钟，请确认重新计价！";
                }

                if (isNeedReprice)
                {
                    #region 获取半小时之内是否已经重新计价过
                    int count = 0;
                    string checksql = string.Format(@"select count(FCPOrderId) as count  from FlightCheckPrice with(nolock) 
                                        where FCPOrderId={0} and FCPCheckDate>'{1}'", orderId, DateTime.Now.AddMinutes(-30));
                    try
                    {
                        DataTable dt = DBHelper.ExecuteDataTable(checksql);
                        count = Convert.ToInt32(dt.Rows[0]["count"]);
                    }
                    catch
                    {
                        count = 0;
                    }
                    #endregion
                    if (count > 0)
                    {
                        msg = string.Empty;
                    }
                }
            }
            return msg;
        }
        #endregion

        #region 根据常用的TCAllianceID获取订单来源，当TCAllianceID不存在常用TCAllianceID中直接返回TCAllianceID
        public static string GetOrderChannelByTCAllianceID(string TCAllianceID)
        {
            string orderChannelDes = TCAllianceID;
            return orderChannelDes;
        }
        #endregion

        #region 根据出生日期计算年龄 格式为：2011-02-20
        /// <summary>
        /// 根据出生日期计算年龄 格式为：2011-02-20
        /// </summary>
        /// <param name="birthday">出生日期（格式为：2011-02-20）</param>
        /// <returns></returns>
        public static int GetAgeByBirthday(string birthday)
        {
            int age = 0;
            try
            {
                DateTime aDate = DateTime.Now;
                int thisYear = aDate.Year;
                int thisMonth = aDate.Month;
                int thisDay = aDate.Day;
                string strBirthDay = Convert.ToDateTime(birthday).ToString("yyyy-MM-dd");
                string[] birthDay = strBirthDay.Split('-');
                if (birthDay.Length == 3)
                {
                    int brithy = TypeParse.StrToInt(birthDay[0], 0);
                    int brithm = TypeParse.StrToInt(birthDay[1], 0);
                    int brithd = TypeParse.StrToInt(birthDay[2], 0);
                    if (thisYear - brithy < 0)
                    {
                        Logger.WriteLog("日期输入错误!");
                    }
                    else
                    {
                        if (thisMonth - brithm < 0)
                        {
                            age = thisYear - brithy - 1;
                        }
                        else
                        {
                            if (thisDay - brithd >= 0)
                            {
                                age = thisYear - brithy;
                            }
                            else
                            {
                                age = thisYear - brithy - 1;
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Logger.WriteLog("根据出生日期计算年龄异常", ex);
            }
            return age;
        }
        #endregion

        #region 根据身份证获取生日和性别
        /// <summary>
        /// 判断身份证是否合法 返回身份证获取生日和性别
        /// </summary>
        /// <param name="cardNo">身份证号码</param>
        /// <param name="cardType">证件类型</param>
        /// <param name="passType">乘客类型（1-成人 2-儿童）</param>
        /// <param name="strBirthDay">生日</param>
        /// <param name="strSex">性别</param>
        /// <returns></returns>
        public static bool GetBirthdayAndSexByCardNo(string cardNo, string cardType, out string strBirthDay, out string strSex)
        {
            string birth = string.Empty;//生日1990-01-01
            string sex = string.Empty;//M男 or F女
            bool isSuccess = false;
            try
            {
                if (cardType == "0")
                {
                    if (cardNo.Length != 15 && cardNo.Length != 18)//身份证号码只能为15位或18位其它不合法
                    {
                        strBirthDay = birth;
                        strSex = sex;
                    }
                    if (cardNo.Length == 18)//处理18位的身份证号码从号码中得到生日和性别代码
                    {
                        birth = cardNo.Substring(6, 4) + "-" + cardNo.Substring(10, 2) + "-" + cardNo.Substring(12, 2);
                        sex = cardNo.Substring(14, 3);
                        isSuccess = true;
                    }
                    if (cardNo.Length == 15)
                    {
                        birth = "19" + cardNo.Substring(6, 2) + "-" + cardNo.Substring(8, 2) + "-" + cardNo.Substring(10, 2);
                        sex = cardNo.Substring(12, 3);
                        isSuccess = true;
                    }
                    if (int.Parse(sex) % 2 == 0)//性别代码为偶数是女性奇数为男性
                    {
                        sex = "F";
                    }
                    else
                    {
                        sex = "M";
                    }
                }
                else
                {
                    birth = DateTime.Now.AddYears(-20).ToString("yyyy-MM-dd");
                    sex = "F";
                    isSuccess = true;
                }
            }
            catch (Exception ex)
            {
                Logger.WriteLog("根据身份证获取生日和性别异常", ex);
            }
            strBirthDay = birth;
            strSex = sex;
            return isSuccess;
        }
        #endregion
    }
}
